<template>
    <div class="loginBox">
        <!-- 表单主体 -->
        <el-form :model="loginForm" :rules="rules" ref="loginRef" label-width="80px" class="loginForm" status-icon>
            <!-- 用户名 -->
            <el-form-item label="用户名" prop="username">
                <el-input v-model="loginForm.username" clearable />
            </el-form-item>

            <!-- 密码 -->
            <el-form-item label="密码" prop="password">
                <el-input type="password" clearable show-password v-model="loginForm.password" />
            </el-form-item>

            <!-- 登录按钮 -->
            <el-form-item>
                <el-button type="primary" @click="enter(loginRef)">登录</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>


<script lang="ts" setup>
//引入数据响应
import { reactive, ref } from "vue";
//引入表单验证规则
import type { FormInstance, FormRules } from 'element-plus';
//引入路由跳转
import { useRouter } from "vue-router";
//引入仓库
import { useStore } from "vuex";

// ===========数据=============
//设置表单数据
let loginForm = reactive({
    username: 'admin',
    password: 'admin888'
});

//设置ref属性
const loginRef = ref<FormInstance>();

//设置路由跳转
const router = useRouter();

//设置表单验证规则
const rules = reactive<FormRules>({
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 2, max: 8, message: '用户名长度应在2-8之间', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 16, message: '密码长度应在6-16之间', trigger: 'blur' },
    ]
});

//设置仓库
const store = useStore();


// ============事件=============
//点击登录事件   formEl 代表的是不是表单ref的那个值 
let enter = (formEl: FormInstance | undefined) => {
    if (formEl) {
        //表单验证 是否填写必须填写的数据
        formEl.validate(val => {
            if (val) {
                store.dispatch('userLogin', loginForm);
                //跳转Index页面
                setTimeout(() => {
                    router.push('/index');
                }, 500);
            };
        });
    };
};


</script>


<style lang="less" scoped>
.loginBox {
    width: 100vw;
    height: 100vh;
    background: url("../assets/img/1.jpg") no-repeat;
    background-size: 100% 100%;

    .loginForm {
        width: 400px;
        height: 200px;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        padding: 20px;
    }
}
</style>